// 2025/3/22
// https://leetcode.cn/problems/decode-string/description/?envType=study-plan-v2&envId=top-100-liked
// 字符串解码

class Solution {
    public:
        string decodeString(string s) {
            int n = s.size(), i = 0;
            string ans;
            stack<int> nums;
            while (i < n)
            {
                if ('0' <= s[i] && s[i] <= '9')
                {
                    int tmp = 0;
                    while ('0' <= s[i] && s[i] <= '9')
                    {
                        tmp *= 10;
                        tmp += s[i] - '0';
                        i++;
                    }
                    nums.push(tmp);
                    nums.push(ans.size());
                }
                else if ('a' <= s[i] && s[i] <= 'z')
                {
                    while ('a' <= s[i] && s[i] <= 'z')
                        ans += s[i++];
                }
                else
                {
                    if (s[i] == ']')
                    {
                        string str(ans.begin() + nums.top(), ans.end());
                        nums.pop();
                        while (--nums.top())
                        {
                            ans += str;
                        }
                        nums.pop();
                    }
                    i++;
                }
            }
            return ans;
        }
    };